//
//  YFPackage.swift
//  Emoji
//
//  Created by 余仿 on 16/4/18.
//  Copyright © 2016年 yf. All rights reserved.
//

import UIKit

class YFPackage: NSObject {

    var name:String?

    var emotions:[[YFEmoji]]?

    init(id:String,name:String,array:[[String:String]]) {

        self.name = name

        super.init()

        //字典数组转成模型数组
        let arrayUnSection = dictToModel(id, array: array)
        //并将[]-转成->[[]]
        emotions = divideArray(arrayUnSection)

    }

    //MARK:字典转模型
    func dictToModel(id:String,array:[[String:String]]) -> [YFEmoji]{

        var tempArray = [YFEmoji]()
        //遍历数组,取出字典


        var count = 0

        for dict in array{

            //字典转模型
            let model = YFEmoji(id: id, dict: dict)

            tempArray.append(model)

            count++

            if count == 20{


                let isDelete = YFEmoji(isDelete: true)

                tempArray.append(isDelete)

                print("come here----\(tempArray.count)")
                
                count = 0
            }
        }

        //用空对象填满页数不足的
        //从第几个到第几个需要设置空模型?
        let startCount = tempArray.count % 21

        if startCount > 0{

            for _ in startCount..<20{

//                if i == 20 {
//
//                let isDelete = YFEmoji(isDelete: true)
//
//                tempArray.append(isDelete)
//
//                }else{

                    //插入空模型
                    let emptyEmoji = YFEmoji(isEmpty: true)

                    tempArray.append(emptyEmoji)

//                }
            }

            //添加完空白表情后添加一个删除表情
            let isDelete = YFEmoji(isDelete: true)
            
            tempArray.append(isDelete)
        }
        
        return tempArray
    }

    //划分模型数组
    func divideArray(array:[YFEmoji]) -> [[YFEmoji]]{

//        每一页取21个,根据页数进行分组
        var tempArray = [[YFEmoji]]()

        let pageCount = (array.count - 1) / 21 + 1

        for index in 0..<pageCount{

            let loc = index * 21

            let len = 21
            //因为最后可能一页并没有21个,直接截取21个会导致数组越界,需要对len进行处理
//            if loc + len > array.count{
//
//                len = array.count - loc
//
//            }

            //截取好的表情小组
            let emojis = (array as NSArray).subarrayWithRange(NSMakeRange(loc, len)) as! [YFEmoji]

            tempArray.append(emojis)
        }

        return tempArray
    }
}
